package com.battle.service.controller.web;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.battle.pojo.entity.Organization;
import com.battle.pojo.entity.Role;
import com.battle.pojo.entity.User;
import com.battle.pojo.entity.UserOrganizationMp;
import com.battle.pojo.enums.resource.ResourceTypeEnum;
import com.battle.pojo.vo.YitihuaPushVo.YitihuaRolePushVo;
import com.battle.pojo.vo.organization.GetOrganizationTreeListVo;
import com.battle.pojo.vo.YitihuaPushVo.YitihuaOrganizationPushVo;
import com.battle.service.repository.in.OrganizationRepository;
import com.battle.service.repository.in.RoleRepository;
import com.battle.service.repository.in.UserOrganizationMpRepository;
import com.battle.service.repository.in.UserRepository;
import com.battle.service.service.in.OrganizationService;
import com.battle.service.service.in.ResourceService;
import com.battle.service.service.in.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import nirvana.core.domains.vo.ApiResult;
import nirvana.core.exceptions.BizException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 一体化推送
 */

@RestController
@RequestMapping("/yitihua/push")
@Configuration
public class YitihuaPushController {
    @Value("${yitihua.push.url}")
    String pushUrl;

    @Value("${yitihua.push.appId}")
    String appId;

    @Value("${yitihua.push.appKey}")
    String appKey;

    final OrganizationService organizationService;
    final OrganizationRepository organizationRepository;
    final ResourceService resourceService;
    final RoleRepository roleRepository;
    final UserService userService;
    final UserRepository userRepository;
    final UserOrganizationMpRepository userOrganizationMpRepository;
    final ObjectMapper objectMapper;

    public YitihuaPushController(OrganizationService organizationService, OrganizationRepository organizationRepository, ResourceService resourceService, RoleRepository roleRepository, UserService userService, UserRepository userRepository, UserOrganizationMpRepository userOrganizationMpRepository, ObjectMapper objectMapper) {
        this.organizationService = organizationService;
        this.organizationRepository = organizationRepository;
        this.resourceService = resourceService;
        this.roleRepository = roleRepository;
        this.userService = userService;
        this.userRepository = userRepository;
        this.userOrganizationMpRepository = userOrganizationMpRepository;
        this.objectMapper = objectMapper;
    }

    /**
     * 一体化推送-资源
     */
    @GetMapping("/resource")
    public ApiResult pushResource() {
        JSONArray jsonArray = resourceService.getResourceTree(ResourceTypeEnum.getList());

        // 推送到一体化
        HttpRequest request = HttpUtil.createPost(pushUrl + "/push/system/resource");
        request.header("appId", appId);
        request.header("appKey", appKey);
        request.body(jsonArray.toString());
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new BizException("推送失败，状态码：" + response.getStatus());
            }
        }
        return ApiResult.ok();
    }

    /**
     * 同步一体化的用户
     */
    @GetMapping("/syncUser")
    @Transactional(rollbackFor = Exception.class)
    public ApiResult syncUser() {
        HttpRequest request = HttpUtil.createPost(pushUrl + "/sync/system/user");
        request.header("appId", appId);
        request.header("appKey", appKey);
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new BizException("获取用户失败，状态码：" + response.getStatus());
            }
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<UserOrganizationMp> organizationMpList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                List<Long> organizationIdList = json.getBeanList("organizationIdList", Long.class);
                for (Long organizationId : organizationIdList) {
                    UserOrganizationMp userOrganizationMp = new UserOrganizationMp();
                    userOrganizationMp.setUserId(json.getLong("id"));
                    userOrganizationMp.setOrganizationId(organizationId);
                    organizationMpList.add(userOrganizationMp);
                }
            }

            List<User> userList = objectMapper.readValue(jsonArray.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, User.class));
            userRepository.saveOrUpdateBatch(userList);

            // 删除原有的用户组织关系
            userOrganizationMpRepository.batchDelete();
            userOrganizationMpRepository.saveBatch(organizationMpList);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ApiResult.ok();
    }

    /**
     * 同步一体化的组织架构
     */
    @GetMapping("/syncOrganization")
    @Transactional(rollbackFor = Exception.class)
    public ApiResult syncOrganization() {
        HttpRequest request = HttpUtil.createPost(pushUrl + "/sync/system/organization");
        request.header("appId", appId);
        request.header("appKey", appKey);
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new BizException("获取组织架构失败，状态码：" + response.getStatus());
            }
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            List<Organization> organizationList = objectMapper.readValue(jsonObject.getJSONArray("data").toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, Organization.class));
            System.out.println(organizationList);
            organizationRepository.saveOrUpdateBatch(organizationList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ApiResult.ok();
    }


}
